#ifndef TCPCONNECTION_H
#define TCPCONNECTION_H
#include "noncopyable.hpp"
#include "inetaddress.hpp"
#include "socket.hpp"
#include "socketio.hpp"
#include "eventloop.hpp"
#include <memory>
#include <string>
#include <functional>
using std::string;

namespace moqi
{
class TcpConnection;
using TcpConnectionPtr = std::shared_ptr<TcpConnection>;
using TcpConnectionCallback = std::function<void(TcpConnectionPtr)>;

class TcpConnection:Noncopyable,
public std::enable_shared_from_this<TcpConnection>
{
public:
    TcpConnection(int fd, EventLoop *loop);
    ~TcpConnection();
    void send(const string& msg);
    void sendInloop(const string& msg);
    string recv();
    void shutdown();
    bool isClosed()const;
    string status()const;
    void setAllCallback(const TcpConnectionCallback &cb1,
                        const TcpConnectionCallback &cb2,
                        const TcpConnectionCallback &cb3
                        )
    {
        _onConnecton = cb1;
        _onMessage = cb2;
        _onClose = cb3;
    }
    void handleConnectionCallback();
    void handleMessageCallback();
    void handleCloseCallback();
    
    void updateActiveTime();
    bool checkTimeOut(int maxInavtiveTime = 30);

private:
    InetAddress getLocalAddr();
    InetAddress getPeerAddr();

private:
    Socket                  _sock;
    SocketIO                _sockio;
    InetAddress             _localAddr;
    InetAddress             _peerAddr;
    EventLoop*              _loop;
    time_t                  _lastActiveTime;//该链接上次活跃时间
    
    TcpConnectionCallback   _onConnecton;
    TcpConnectionCallback   _onMessage;
    TcpConnectionCallback   _onClose;
};

}

#endif

